//
//  SynTask.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-5-23.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "SynTask.h"
#import "WebServiceHelper.h"
#import "GDataXMLNode.h"
#import "EPXMLService.h"
#import "CategoryInfoModel.h"
#import "StringUtil.h"
#import <sqlite3.h>
#import "DbUtil.h"
#import "UserInfoModel.h"
#import "PinYinUtil.h"
#import "OuInfoModel.h"
#import "DateUtil.h"
#import "DBFrameService.h"
#import "TKAlertCenter.h"
#import "UITool.h"

@implementation SynTask

-(void)execute
{
    if ([self synAllUsers]==NO) {
        return;
    }
    
    if ([self synAllOu]==NO) {
        return;
    }
    
    if ([self synWebInfoCategory]==NO) {
        return;
    }
    
    [UITool toast_mul:@"数据同步成功"];
    
    [self sendDataRefreshUI:@""];
}

-(BOOL)synAllOu
{
    NSString *ValidateData = [self.params objectForKey:@"ValidateData"];
    NSString *url = [self.params objectForKey:@"url"];
    NSString *wsNamespace = [self.params objectForKey:@"namespace"];
    NSString *userguid = [self.params objectForKey:@"userguid"];
    WebServiceHelper *webserviceHelper = [[WebServiceHelper alloc]initWebServiceWithUrl:url wsNamespace:wsNamespace method:@"Address_GetAllOUList"];
    
    NSString *ParasXml = @"<?xml version=\"1.0\" encoding=\"gb2312\"?><paras><UserGuid>%@</UserGuid><ParentOUGuid></ParentOUGuid></paras>";
    ParasXml = [[ParasXml stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"]stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    ParasXml = [NSString stringWithFormat:ParasXml,userguid];
    [webserviceHelper addParameterForString:@"ValidateData" value:ValidateData];
    [webserviceHelper addParameterForString:@"ParasXml" value:ParasXml];
    NSString *bs = webserviceHelper.start;
    if (![EPXMLService validateXML:bs]) {
        return NO;
    }
    
    NSString *xmldata = [StringUtil getXMLFormatedAttribute:bs :@"UserArea"];
    GDataXMLDocument *doc = [[[GDataXMLDocument alloc] initWithXMLString:xmldata  options:0 error:nil]autorelease];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *arrays = [rootElement elementsForName:@"OuInfo"];
    NSMutableArray *listmp = [[NSMutableArray alloc]init];
    for (GDataXMLElement *arr in arrays)
    {
        OuInfoModel *m = [[OuInfoModel alloc]init];
        GDataXMLElement *OUGuid = [[arr elementsForName:@"OUGuid"] objectAtIndex:0];
        m.OUGuid = [OUGuid stringValue];
        GDataXMLElement *OUName = [[arr elementsForName:@"OUName"] objectAtIndex:0];
        m.OUName = [OUName stringValue];
        GDataXMLElement *HasChildUser = [[arr elementsForName:@"HasChildUser"] objectAtIndex:0];
        m.HasChildUser = [HasChildUser stringValue];
        GDataXMLElement *HasChildOu = [[arr elementsForName:@"HasChildOu"] objectAtIndex:0];
        m.HasChildOu = [HasChildOu stringValue];
        GDataXMLElement *ParentOUGuid = [[arr elementsForName:@"ParentOUGuid"] objectAtIndex:0];
        m.ParentOUGuid = [ParentOUGuid stringValue];
        [listmp addObject:m];
        [m release];
    }
    NSLog(@"ou count:%i",listmp.count);
    [self setAllOuArray:listmp];
    [listmp release];
    
    [DBFrameService setConfigValue:EP_ConfigKey_syntime value:[DateUtil getCurrentTimeStr]];
    return YES;
}

-(BOOL)synAllUsers
{
    NSString *ValidateData = [self.params objectForKey:@"ValidateData"];
    NSString *url = [self.params objectForKey:@"url"];
    NSString *wsNamespace = [self.params objectForKey:@"namespace"];
    NSString *userguid = [self.params objectForKey:@"userguid"];
    WebServiceHelper *webserviceHelper = [[WebServiceHelper alloc]initWebServiceWithUrl:url wsNamespace:wsNamespace method:@"Address_GetAllUserList"];
    
    NSString *ParasXml = @"<?xml version=\"1.0\" encoding=\"gb2312\"?><paras><UserGuid>%@</UserGuid><KeyWord></KeyWord><ParentOUGuid></ParentOUGuid></paras>";
    ParasXml = [[ParasXml stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"]stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    ParasXml = [NSString stringWithFormat:ParasXml,userguid];
    [webserviceHelper addParameterForString:@"ValidateData" value:ValidateData];
    [webserviceHelper addParameterForString:@"ParasXml" value:ParasXml];
    NSString *bs = webserviceHelper.start;
    if (![EPXMLService validateXML:bs]) {
        return NO;
    }
    
    NSString *xmldata = [StringUtil getXMLFormatedAttribute:bs :@"UserArea"];
    GDataXMLDocument *doc = [[[GDataXMLDocument alloc] initWithXMLString:xmldata  options:0 error:nil]autorelease];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *arrays = [rootElement elementsForName:@"UserInfo"];
    NSMutableArray *listmp = [[NSMutableArray alloc]init];
    for (GDataXMLElement *arr in arrays)
    {
        UserInfoModel *m = [[UserInfoModel alloc]init];
        GDataXMLElement *UserGuid = [[arr elementsForName:@"UserGuid"] objectAtIndex:0];
        m.UserGuid = [UserGuid stringValue];
        GDataXMLElement *DisplayName = [[arr elementsForName:@"DisplayName"] objectAtIndex:0];
        m.DisplayName = [DisplayName stringValue];
        GDataXMLElement *OUGuid = [[arr elementsForName:@"OUGuid"] objectAtIndex:0];
        m.OUGuid = [OUGuid stringValue];
        GDataXMLElement *OrderNumber = [[arr elementsForName:@"OrderNumber"] objectAtIndex:0];
        m.OrderNumber = [OrderNumber stringValue];
        GDataXMLElement *Title = [[arr elementsForName:@"Title"] objectAtIndex:0];
        m.Title = [Title stringValue];
        GDataXMLElement *TelephoneOffice = [[arr elementsForName:@"TelephoneOffice"] objectAtIndex:0];
        m.TelephoneOffice = [TelephoneOffice stringValue];
        GDataXMLElement *TelephoneHome = [[arr elementsForName:@"TelephoneHome"] objectAtIndex:0];
        m.TelephoneHome = [TelephoneHome stringValue];
        GDataXMLElement *Mobile = [[arr elementsForName:@"Mobile"] objectAtIndex:0];
        m.Mobile = [Mobile stringValue];
        GDataXMLElement *Email = [[arr elementsForName:@"Email"] objectAtIndex:0];
        m.Email = [Email stringValue];
        GDataXMLElement *Sex = [[arr elementsForName:@"Sex"] objectAtIndex:0];
        m.Sex = [Sex stringValue];
        GDataXMLElement *Fax = [[arr elementsForName:@"Fax"] objectAtIndex:0];
        m.Fax = [Fax stringValue];
        [listmp addObject:m];
        [m release];
    }
        NSLog(@"user count:%i",listmp.count);
    [self setAllUserArray:listmp];
    [listmp release];
    return YES;
}

-(BOOL)synWebInfoCategory
{
    NSString *ValidateData = [self.params objectForKey:@"ValidateData"];
    NSString *url = [self.params objectForKey:@"url"];
    NSString *wsNamespace = [self.params objectForKey:@"namespace"];
    WebServiceHelper *webserviceHelper = [[WebServiceHelper alloc]initWebServiceWithUrl:url wsNamespace:wsNamespace method:@"WebInfo_GetCateGoryTree"];
    
    NSString *ParasXml = @"&lt;?xml version=\"1.0\" encoding=\"gb2312\"?&gt;&lt;paras&gt;&lt;UserGuid&gt;%@&lt;/UserGuid&gt;&lt;/paras&gt;";
    ParasXml = [NSString stringWithFormat:ParasXml,[DBFrameService getConfigValue:EP_ConfigKey_userguid]];
    
    [webserviceHelper addParameterForString:@"ValidateData" value:ValidateData];
    [webserviceHelper addParameterForString:@"ParasXml" value:ParasXml];
    NSString *bs = webserviceHelper.start;
    
    if (![EPXMLService validateXML:bs]) {
        return NO;
    }
    
    NSString *xmldata = [StringUtil getXMLFormatedAttribute:bs :@"UserArea"];
    GDataXMLDocument *doc = [[[GDataXMLDocument alloc] initWithXMLString:xmldata  options:0 error:nil]autorelease];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *arrays = [rootElement elementsForName:@"CateGoryInfo"];
    NSMutableArray *listmp = [[NSMutableArray alloc]init];
    for (GDataXMLElement *arr in arrays)
    {
        CategoryInfoModel *model = [[CategoryInfoModel alloc]init];
        GDataXMLElement *CategoryName = [[arr elementsForName:@"CategoryName"] objectAtIndex:0];
        model.CategoryName = [CategoryName stringValue];
        GDataXMLElement *CategoryGuid = [[arr elementsForName:@"CategoryGuid"] objectAtIndex:0];
        model.CategoryGuid = [CategoryGuid stringValue];
        GDataXMLElement *IsTongzhiGongGao = [[arr elementsForName:@"IsTongzhiGongGao"] objectAtIndex:0];
        model.IsTongzhiGongGao = [IsTongzhiGongGao stringValue];
        GDataXMLElement *ParentCategoryGuid = [[arr elementsForName:@"ParentCategoryGuid"] objectAtIndex:0];
        model.ParentCategoryGuid = [ParentCategoryGuid stringValue];
        [listmp addObject:model];
        [model release];
    }
    [self setWebInfoCategoryArray:listmp];
    NSLog(@"webinfocateogory count:%i",listmp.count);
    [listmp release];
    return YES;
}

-(void)setWebInfoCategoryArray:(NSMutableArray*)dataArray
{
    sqlite3 *framedb = [DbUtil getFrameDB];
    char *errorMsg;
    const char *begin = "BEGIN TRANSACTION", *end = "COMMIT";
    sqlite3_stmt *beginStmt = NULL, *endStmt = NULL;
    
    sqlite3_prepare_v2(framedb, begin, strlen(begin), &beginStmt, NULL);
    sqlite3_step(beginStmt);
    sqlite3_finalize(beginStmt);
    
    sqlite3_exec(framedb, [@"delete from webinfo_category" UTF8String], NULL, NULL, &errorMsg);
    
    for (int i=0; i<dataArray.count; i++) {
        CategoryInfoModel *m = [dataArray objectAtIndex:i];
        NSString *insertSql = [NSString stringWithFormat:@"insert into webinfo_category values('%@','%@','%@','%@')",m.CategoryName,m.CategoryGuid,m.ParentCategoryGuid,m.IsTongzhiGongGao];
        sqlite3_exec(framedb, [insertSql UTF8String], NULL, NULL, &errorMsg);
    }
    sqlite3_prepare_v2(framedb, end, strlen(end), &endStmt, NULL);
    sqlite3_step(endStmt);
    sqlite3_finalize(endStmt);
    sqlite3_close(framedb);
}

-(void)setAllUserArray:(NSMutableArray*)dataArray
{
    sqlite3 *framedb = [DbUtil getFrameDB];
    char *errorMsg;
    const char *begin = "BEGIN TRANSACTION", *end = "COMMIT";
    sqlite3_stmt *beginStmt = NULL, *endStmt = NULL;
    
    sqlite3_prepare_v2(framedb, begin, strlen(begin), &beginStmt, NULL);
    sqlite3_step(beginStmt);
    sqlite3_finalize(beginStmt);
    
    sqlite3_exec(framedb, [@"delete from user" UTF8String], NULL, NULL, &errorMsg);
    
    for (int i=0; i<dataArray.count; i++) {
        UserInfoModel *m = [dataArray objectAtIndex:i];
        NSString *py = [PinYinUtil Hanzi2PinYin:m.DisplayName];
        NSString *insertSql = [NSString stringWithFormat:@"insert into user values(%@,'%@','%@','%@','%@','%@','%@',%@,'%@','%@','%@','%@',%@,%@,%@,'%@')",
                               @"null",m.UserGuid,m.OUGuid,m.DisplayName,m.Mobile,m.TelephoneOffice,m.Title,@"null",m.Fax,m.Sex,m.Email,m.TelephoneHome,@"null",@"null",@"null",py];
        sqlite3_exec(framedb, [insertSql UTF8String], NULL, NULL, &errorMsg);
    }
    sqlite3_prepare_v2(framedb, end, strlen(end), &endStmt, NULL);
    sqlite3_step(endStmt);
    sqlite3_finalize(endStmt);
    sqlite3_close(framedb);
}

-(void)setAllOuArray:(NSMutableArray*)dataArray
{
    sqlite3 *framedb = [DbUtil getFrameDB];
    char *errorMsg;
    const char *begin = "BEGIN TRANSACTION", *end = "COMMIT";
    sqlite3_stmt *beginStmt = NULL, *endStmt = NULL;
    
    sqlite3_prepare_v2(framedb, begin, strlen(begin), &beginStmt, NULL);
    sqlite3_step(beginStmt);
    sqlite3_finalize(beginStmt);
    
    sqlite3_exec(framedb, [@"delete from ou" UTF8String], NULL, NULL, &errorMsg);
    
    for (int i=0; i<dataArray.count; i++) {
        OuInfoModel *m = [dataArray objectAtIndex:i];
        NSString *py = [PinYinUtil Hanzi2PinYin:m.OUName];
        NSString *insertSql = [NSString stringWithFormat:@"insert into ou values('%@','%@','%@','%@')",
                               m.OUGuid,m.OUName,m.ParentOUGuid,py];
        sqlite3_exec(framedb, [insertSql UTF8String], NULL, NULL, &errorMsg);
    }
    sqlite3_prepare_v2(framedb, end, strlen(end), &endStmt, NULL);
    sqlite3_step(endStmt);
    sqlite3_finalize(endStmt);
    sqlite3_close(framedb);
    
    if (errorMsg!=NULL) {
        NSLog(@"ERR:%s",errorMsg);
    }
}

@end
